import React, { useState, useEffect, useLayoutEffect } from "react";
import { Button } from "antd";
import "./Demo1.less";

const Demo = function Demo(props) {
  console.log("render"); //  每次都执行两次
  let [num, setNum] = useState(0);

  const handle = () => {
    setNum(0);
  };

  // 使用这种形式，他是在页面渲染完成之后在进行更新的
  // useEffect(() => {
  //   if (num === 0) {
  //     setNum(10);
  //   }
  // }, [num]);

  useLayoutEffect(() => {
    if (num === 0) {
      // setNum(10);
      console.log("useLayoutEffect"); // 先执行
    }
  }, [num]);

  useEffect(() => {
    if (num === 0) {
      // setNum(10);
      console.log("useEffect"); // 后执行
    }
  }, [num]);

  return (
    <div className="demo">
      <span className="num" style={{ color: num === 0 ? "red" : "green" }}>
        {num}
      </span>
      <Button type="primary" size="small" onClick={handle}>
        新增
      </Button>
    </div>
  );
};

export default Demo;
